package com.netty.server;

import com.netty.client.handler.TestHandler;
import com.netty.common.codec.ImFrameDecoder;
import com.netty.common.codec.PacketCodecHandler;
import com.netty.common.commonhandler.ImIdleStateHandler;
import com.netty.server.handler.HeartBeatRequestHandler;
import com.netty.server.handler.LoginRequestHandler;
import com.netty.server.handler.MessageRequestHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Netty服务器端
 *
 * @author Chenwj
 */
public class NettyServer {
    public static void main(String[] args) {
        // Netty中用于启动服务器的辅助类，它提供了一系列配置服务器参数的方法
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 接受客户端连接
        NioEventLoopGroup boss = new NioEventLoopGroup();
        // 处理已经被接受的连接的I/O
        NioEventLoopGroup worker = new NioEventLoopGroup();

        // 配置ServerBootstrap
        serverBootstrap
                .group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) {
                        // 聊天空闲检测器
                        ch.pipeline().addLast(new ImIdleStateHandler());
                        // 拆包器
                        ch.pipeline().addLast(new ImFrameDecoder());
                        // ch.pipeline().addLast(new PacketDecoder());
                        // 处理数据的编码和解码
                        ch.pipeline().addLast(PacketCodecHandler.INSTANCE);
                        // 处理登录
                        ch.pipeline().addLast(LoginRequestHandler.INSTANCE);
                        // 处理心跳
                        ch.pipeline().addLast(HeartBeatRequestHandler.INSTANCE);
                        ch.pipeline().addLast(new TestHandler());
                        // 处理消息
                        ch.pipeline().addLast(MessageRequestHandler.INSTANCE);
                        // ch.pipeline().addLast(new PacketEncoder());
                    }
                });

        // 绑定端口并启动服务器
        serverBootstrap
                .bind(9000)
                .addListener(future -> {
                    if (future.isSuccess()) {
                        System.out.println("端口9000绑定成功！");
                    } else {
                        System.err.println("端口9000绑定失败！");
                    }
                });
    }
}

